﻿using Microsoft.Extensions.FileProviders;
using Quickly.Identity.API.Endpoints;

namespace Quickly.Identity.API;

public static class DependencyInjectionExtensions
{
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
    {
        return collection is null || collection.Any() == false;
    }

    public static IApplicationBuilder UseHostFrontendIfConfigured(this WebApplication app)
    {
        var section = app.Configuration.GetSection("HostFrontend");
        if (section != null)
        {
            var hostOptions = new HostFrontendOption();
            section.Bind(hostOptions);

            // validate
            var result = hostOptions.Validate();

            if (result.IsValid)
            {
                var fullPath = Path.Combine(app.Environment.ContentRootPath, hostOptions.PhysicalPath!);

                if (Directory.Exists(fullPath))
                {
                    var options = new FileServerOptions()
                    {
                        FileProvider = new PhysicalFileProvider(fullPath),
                        RequestPath = hostOptions.RequestPath ?? string.Empty
                    };

                    if (hostOptions.DefaultFiles?.IsNullOrEmpty() ?? false)
                    {
                        options.DefaultFilesOptions.DefaultFileNames.Add("index.html");
                    }
                    else
                    {
                        foreach (var item in hostOptions.DefaultFiles!)
                        {
                            options.DefaultFilesOptions.DefaultFileNames.Add(item);
                        }
                    }

                    app.UseFileServer(options);
                }
                else
                {
                    app.Logger.LogError("承载前端的物理路径不存在：{Path}", fullPath);
                }
            }
            else
            {
                app.Logger.LogWarning("未应用前端承载配置：{@Errors}", result.Errors);
            }
        }

        return app;
    }

    public static WebApplication MapIdentityManageApi(this WebApplication app) => MapIdentityManageApi<AppUser, AppRole>(app);
    public static WebApplication MapIdentityManageApi<TUser, TRole>(this WebApplication app) where TUser : class where TRole : class
    {
        var usersManage = app.NewVersionedApi();

        var v1 = usersManage.MapGroup("/api/identity/v{version:apiVersion}")
            .HasApiVersion(SupportApiVersions.V1);

        v1.MapGroup("/account/manage").MapUserManageApiEndpoints<TUser>();
        v1.MapGroup("/role/manage").MapRoleManageEndpoints<TRole>();

        return app;
    }

    public static WebApplication MapQuickIdentityEndpoints(this WebApplication app)
    {
        var defaultEndpoints = app.NewVersionedApi();
        var v2 = defaultEndpoints.MapGroup("/api/identity/v{version:apiVersion}")
            .HasApiVersion(SupportApiVersions.V2);

        v2.MapDefaultEndpoints();

        return app;
    }
}
